package com.zsyh.jiujiu.home;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.bumptech.glide.Glide;
import com.example.zyh.toolslib.base.BaseActivity;
import com.example.zyh.toolslib.utils.EmptyUtil;
import com.example.zyh.toolslib.utils.SPUtils;
import com.google.gson.Gson;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.lwb.retrofit.RetrofitTask;
import com.zsyh.jiujiu.Adress.FabuAdress;
import com.zsyh.jiujiu.Adress.SelectAddresFinish;
import com.zsyh.jiujiu.Api;
import com.zsyh.jiujiu.R;
import com.zsyh.jiujiu.bean.MyInfoBeeean;
import com.zsyh.jiujiu.dialog.ClallBackData;
import com.zsyh.jiujiu.dialog.TianXieDialog;
import com.zsyh.jiujiu.dialog.TimeSelectDialog;
import com.zsyh.jiujiu.net.MyObserver;
import com.zsyh.jiujiu.utils.CompressPhotoUtils;
import com.zsyh.jiujiu.utils.GlideCircleTransform;
import com.zsyh.jiujiu.utils.GlideEngine;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * @ProjectName: livvehelp
 * @Package: com.zsyh.lsb.ui
 * @ClassName:
 * @Description: java类作用描述
 * @Author: zsyh
 * @CreateDate: 2020/9/7 11:59
 * @UpdateUser: liangwanbo
 * @UpdateDate: 2020/9/7 11:59
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class MyInfoActivity extends BaseActivity {

    @BindView(R.id.regerenback)
    RelativeLayout regerenback;
    @BindView(R.id.ttouxiang)
    ImageView ttouxiang;
    @BindView(R.id.imagexiangji)
    ImageView imagexiangji;
    @BindView(R.id.modifytou)
    RelativeLayout modifytou;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.rename)
    RelativeLayout rename;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.rephone)
    RelativeLayout rephone;
    @BindView(R.id.renzheng)
    TextView renzheng;
    @BindView(R.id.reshiming)
    RelativeLayout reshiming;
    @BindView(R.id.readress)
    RelativeLayout readress;
    @BindView(R.id.reloginpassword)
    RelativeLayout reloginpassword;
    @BindView(R.id.resex)
    RelativeLayout resex;
    @BindView(R.id.birday)
    TextView birday;
    @BindView(R.id.rebirsthday)
    RelativeLayout rebirsthday;
    @BindView(R.id.qqnumber)
    TextView qqnumber;
    @BindView(R.id.reQQ)
    RelativeLayout reQQ;
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.recity)
    RelativeLayout recity;
    @BindView(R.id.checknv)
    CheckBox checknv;
    @BindView(R.id.checknan)
    CheckBox checknan;
    private String provinceCode, cityCode, provincename, cityname;
    String userId;
    String headImg;
    String nicknamecanshu;
    String userName;
    String userIdcard;
    String userSex;
    String qqnum;
    String birthday;
    String province;
    String citycanshu;
    String state;

    @Override
    protected int initLayout() {
        return R.layout.activity_myinfo;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        userId = (String) SPUtils.get(thisActivity, "userid", "");
        gettUser((String) SPUtils.get(thisActivity, "userid", ""));
    }

    @Override
    protected void initEvent() {

    }


    @OnClick({R.id.checknv,R.id.checknan,R.id.regerenback, R.id.modifytou, R.id.rename, R.id.rephone, R.id.reshiming, R.id.readress, R.id.reloginpassword, R.id.rebirsthday, R.id.reQQ, R.id.recity})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.checknv:
                if(checknv.isChecked()){
                    checknv.setChecked(true);
                    checknan.setChecked(false);
                    userSex="女";
                }else {
                    checknan.setChecked(false);
                    userSex="女";
                }
                MyInfo(userId,
                        headImg,
                        nicknamecanshu,
                        userName,
                        userIdcard,
                        userSex,
                        qqnum,
                        birthday,
                        province,
                        citycanshu
                );
                break;
            case R.id.checknan:
                if(checknan.isChecked()){
                    checknan.setChecked(true);
                    checknv.setChecked(false);
                    userSex="男";
                }else {
                    checknv.setChecked(false);
                    userSex="男";
                }
                MyInfo(userId,
                        headImg,
                        nicknamecanshu,
                        userName,
                        userIdcard,
                        userSex,
                        qqnum,
                        birthday,
                        province,
                        citycanshu
                );
                break;
            case R.id.regerenback:
                thisActivity.finish();
                break;
            case R.id.modifytou:
                EasyPhotos.createAlbum(thisActivity, true, GlideEngine.getInstance())
                        .setFileProviderAuthority("com.zsyh.jiujiu.fileprovider")
                        .setCount(1)
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                Glide.with(thisActivity)
                                        .load(photos.get(0).path)
                                        .transform(new GlideCircleTransform(thisActivity))
                                        .into(ttouxiang);
                                List<String> list=new ArrayList<>();
                                list.add(photos.get(0).path);
                                UpImage(list);
                            }
                        });
                break;
            case R.id.rename:
                TianXieDialog tianXieDialog = new TianXieDialog("昵称修改：");
                tianXieDialog.setSelectAddresFinish(new ClallBackData() {
                    @Override
                    public void getData(String data, String name, String number) {
                        nicknamecanshu = data;
                        MyInfo(userId,
                                headImg,
                                nicknamecanshu,
                                userName,
                                userIdcard,
                                userSex,
                                qqnum,
                                birthday,
                                province,
                                citycanshu
                        );
                    }
                });
                tianXieDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.rephone:
               /* TianXieDialog tianXieDialogphone = new TianXieDialog("绑定手机号：");
                tianXieDialogphone.setSelectAddresFinish(new ClallBackData() {
                    @Override
                    public void getData(String data, String name, String number) {

                    }
                });
                tianXieDialogphone.show(getSupportFragmentManager(), "");*/
                break;
            case R.id.reshiming:
                Bundle bundleservise = new Bundle();
                bundleservise.putString("name", userName);
                bundleservise.putString("cardid",userIdcard);
                bundleservise.putString("state",state);
                ActivityUtils.startActivity(bundleservise,CardActtivity.class);
                break;
            case R.id.readress:
                ActivityUtils.startActivity(AdressManger.class);
                break;
            case R.id.reloginpassword:
                ActivityUtils.startActivity(ModifyPassword.class);
                break;
            case R.id.rebirsthday:
                TimeSelectDialog timeSelectDialog = new TimeSelectDialog(false);
                timeSelectDialog.setSelectAddresFinish(new ClallBackData() {
                    @Override
                    public void getData(String data, String name, String number) {
                        birday.setText(data);
                        MyInfo(userId,
                                headImg,
                                nicknamecanshu,
                                userName,
                                userIdcard,
                                userSex,
                                qqnum,
                                data,
                                province,
                                citycanshu
                        );
                    }
                });
                timeSelectDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.reQQ:

                TianXieDialog tianXieDialogqq = new TianXieDialog("绑定QQ：");
                tianXieDialogqq.setSelectAddresFinish(new ClallBackData() {
                    @Override
                    public void getData(String data, String name, String number) {
                        qqnum = data;
                        MyInfo(userId,
                                headImg,
                                nicknamecanshu,
                                userName,
                                userIdcard,
                                userSex,
                                qqnum,
                                birthday,
                                province,
                                citycanshu
                        );
                    }
                });
                tianXieDialogqq.show(getSupportFragmentManager(), "");

                break;
            case R.id.recity:
                FabuAdress pop = new FabuAdress(this);
                pop.setSelectAddresFinish(new SelectAddresFinish() {
                    @Override
                    public void finish(String provinceCode, String cityCode, String areaCode, String provincename, String cityname, String areaname) {
                        provinceCode = provinceCode;
                        cityCode = cityCode;
                        province = provincename;
                        citycanshu = cityname;

                        city.setText(provincename + cityname + areaname);
                        MyInfo(userId,
                                headImg,
                                nicknamecanshu,
                                userName,
                                userIdcard,
                                userSex,
                                qqnum,
                                birthday,
                                province,
                                citycanshu
                        );
                    }
                });
                pop.show(getFragmentManager(), "address");
                break;
        }
    }

    /**
     * getuser
     */
    public void gettUser(String userid) {
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .getUserById(userid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this, false) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("Myinfo", JsonStr + "");
                        Gson gson = new Gson();
                        MyInfoBeeean myInfoBeeean = gson.fromJson(JsonStr, MyInfoBeeean.class);
                        nickname.setText(myInfoBeeean.getData().getNickname());
                        phone.setText(myInfoBeeean.getData().getPhone());
                        Glide.with(thisActivity)
                                .load(myInfoBeeean.getData()
                                        .getHeadImg())
                                .transform(new GlideCircleTransform(thisActivity))
                                .into(ttouxiang);
                        birday.setText(myInfoBeeean.getData().getUserBirthday());
                        qqnumber.setText(myInfoBeeean.getData().getQqnum());
                        city.setText(myInfoBeeean.getData().getUserProvince()+" "+ myInfoBeeean.getData().getUserCity()+"");
                        if(!EmptyUtil.isEmpty(myInfoBeeean.getData().getUserSex())){
                            if(myInfoBeeean.getData().getUserSex().equals("男")){
                                checknan.setChecked(true);
                            }else{
                                checknv.setChecked(true);
                            }
                        }

                        userName=myInfoBeeean.getData().getUserName();
                        userIdcard=myInfoBeeean.getData().getUserIdcard();
                        state=myInfoBeeean.getData().getIsCheck();
                    }
                });
    }

    /**
     * 修改信息
     */
    public void MyInfo(String userId,
                       String headImg,
                       String nickname,
                       String userName,
                       String userIdcard,
                       String userSex,
                       String qqnum,
                       String birthday,
                       String province,
                       String city) {
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .updateUser(userId,
                        headImg,
                        nickname,
                        userName,
                        userIdcard,
                        userSex,
                        qqnum,
                        birthday,
                        province,
                        city)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this, false) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("xiugaixinxi", JsonStr + "");
                        Gson gson = new Gson();
                        MyInfoBeeean myInfoBeeean = gson.fromJson(JsonStr, MyInfoBeeean.class);


                    }
                });

    }

    public void UpImage(List<String> list) {
        new CompressPhotoUtils().CompressPhoto(this, list, new CompressPhotoUtils.CompressCallBack() {
            @Override
            public void success(List<String> list) {
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM);//表单类型
                //多张图片
                for (int i = 0; i < list.size(); i++) {
                    File file = new File(list.get(i));//filePath 图片地址
                    RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                    builder.addFormDataPart("file", file.getName(), imageBody);//"imgfile"+i 后台接收图片流的参数名
                }
                List<MultipartBody.Part> parts = builder.build().parts();
                RetrofitTask.getInstance()
                        .createApi(Api.class)
                        .upload(parts)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<ResponseBody>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                try {
                                    String body=responseBody.string();
                                    JSONArray jsonArray=new JSONArray(body);
                                    String imageurl="";
                                    for(int i=0;i<jsonArray.length();i++){
                                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                                        if(i==jsonArray.length()-1){
                                            imageurl=imageurl+jsonObject.getString("url");
                                        }else{
                                            imageurl=imageurl+jsonObject.getString("url")+",";
                                        }
                                    }

                                    MyInfo(userId,
                                            imageurl,
                                            nicknamecanshu,
                                            userName,
                                            userIdcard,
                                            userSex,
                                            qqnum,
                                            birthday,
                                            province,
                                            citycanshu
                                    );

                                    Log.e("body",body+"");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("imageerror",e.getMessage());

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

            }
        });
    }
}
